import { Button, Dialog, Form, Input, Upload } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid } from '../stores/definitions_entrance';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import styles from './EntranceLogo.module.scss';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 16,
  },
  style: { marginBottom: 20 },
};

const EntranceLogo = ({ dictInfo, modal, onCancel, onSubmit, handleCustomRequest }) => {
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal[0] === 'viewLogo');
  const formProps = isViewMode ? { field: false } : {};
  const [entrance] = useState(() => observable({}));
  const uploaderRef = useRef();
  const [disabledAdd, setDisabledAdd] = useState(false);

  useEffect(() => { if (modal[1]?.startsWith?.('toClose') || modal[2]?.startsWith?.('toClose')) handleCancel(); }, [modal]);
  useEffect(() => {
    if (JSON.stringify(dictInfo) === '{}') {
      editCtx.origin = _.cloneDeep({});
      _.assign(entrance, {});
      _.set(entrance, 'disabled', false);
      _.set(entrance, 'sortWeight', 1);
    } else {
      (async () => {
        const res = dictInfo;
        editCtx.origin = _.cloneDeep(res);
        _.assign(entrance, res);
        const { extras } = res;
        const image = extras.image.value;
        _.set(entrance, 'extra.image.value', JSON.parse(image));
        if (JSON.parse(image).length !== 0) {
          setDisabledAdd(true);
        }
      })();
    }
  }, []);

  if (!entrance) return <></>;

  const overrideModel = {
    itemId: {
      label: t`标识`,
      ui: {
        renderer: (v) => <Input value={v} placeholder="请输入标识" readOnly={JSON.stringify(dictInfo) !== '{}'} />,
      },
    },
    name: {
      label: t`名称`,
      ui: {
        renderer: (v) => <Input value={v} placeholder="请输入名称" />,
      },
    },
    extra: {
      image: {
        value: {
          ui: {
            renderer: (r) => {
              const img = r?.map((item) => {
                if (item.originFileObj) {
                  return item;
                }
                return ({
                  uid: item.uid,
                  state: 'done',
                  name: item.name,
                  type: item.type,
                  url: `${API_BASE}/api/files/${item.uid}`,
                  downloadURL: `${API_BASE}/api/files/${item.uid}`,
                  imgURL: `${API_BASE}/api/files/${item.uid}`,
                });
              });
              return (
                <Upload.Card
                  listType="card"
                  className={disabledAdd ? styles.disabled_add : styles.container}
                  value={img}
                  name="extra.image.value"
                  autoUpload={false}
                  beforeUpload={beforeUpload}
                  headers={{ Authorization: `Bearer ${TOKEN}` }}
                  data={(file) => {
                    return { binaryId: file.uid, mimeType: file.type };
                  }}
                  onPreview={handlePreview}
                  ref={saveUploaderRef}
                  formatter={(res, files) => {
                    return {
                      uid: files.uid,
                      name: files.name,
                      state: 'done',
                      type: files.type,
                      url: `${API_BASE}/api/files/${files.uid}`,
                      downloadURL: `${API_BASE}/api/files/${files.uid}`,
                      imgURL: `${API_BASE}/api/files/${files.uid}`,
                    };
                  }}
                  useDataURL
                  request={customRequest}
                  action={`${API_BASE}/upload`}
                  accept="image/png"
                />
              );
            },
          },
        },
      },
    },
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(entrance, name, value);
    if (name === 'extra.image.value') {
      if (value?.length > 0) {
        setDisabledAdd(true);
      } else {
        setDisabledAdd(false);
      }
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handlePreview = ({ url }) => {
    Dialog.show({
      title: t`预览`,
      content: <img src={url} style={{ maxWidth: '800px', width: '100%', height: '100%', objectFit: 'cover' }} />,
      footer: false,
    });
  };

  const saveUploaderRef = (ref) => {
    if (ref) uploaderRef.current = ref.getInstance();
  };

  const beforeUpload = (info, options) => {
    return options;
  };

  const customRequest = (data) => {
    handleCustomRequest(data);
  };

  /**
   * @description 提交表单实现修改配置
   * @param {*} r formData
   */
  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const { extra } = entrance;
    const toggleExtras = extra.image?.value?.map(({ name, uid, type }) => ({ name, uid, type }));
    _.set(entrance, 'extras.image.value', JSON.stringify(toggleExtras));
    onSubmit?.(entrance);
    uploaderRef.current && uploaderRef.current.startUpload();
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={entrance}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={entrance}
        mode={isViewMode ? 'view' : 'edit'}
        columns={1}
        overrideModel={overrideModel}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        fields={[
          'itemId', 'name', 'disabled', 'sortWeight', 'extra.image.value',
        ]}
      />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};
export default observer(EntranceLogo);
